import { defineStore } from "pinia";

interface DictItem {
  key: string;
  value: any;
}
interface DictState {
  dictList: DictItem[];
  lastUpdateTime: number;
}
export const useDictStore = defineStore({
  id: 'app-dict',
  state: (): DictState => ({
    dictList: [],
    lastUpdateTime: 0,
  }),
  getters: {
    getDictList(state) {
      return state.dictList;
    },
    getLastUpdateTime(state) {
      return state.lastUpdateTime;
    },
  },
  actions:{
    //获取字典
    getDict(_key) {
      const item = this.dictList.find((item) => item.key === _key);
      return item ? item.value : null;
    },
    //设置字典
    setDict(_key, value) {
      if (_key !== null && _key !== "") {
        this.dictList.push({
          key: _key,
          value: value
        });
      }
    },
    //删除字典
    delDict(_key) {
      const index = this.dictList.findIndex((item) => item.key === _key);
      if (index !== -1) {
        this.dictList.splice(index, 1);
      }
    },
    //更新字典
    updateDict(_key, value) {
      const item = this.dictList.find((item) => item.key === _key);
      if (item) {
        item.value = value;
      }
    },
    //更新时间
    updateLastUpdateTime() {
      this.lastUpdateTime = new Date().getTime();
    },
    //清空字典
    clearDict() {
      this.dictList = [];
      this.updateLastUpdateTime();
    }
  }
})

export function useDictStoreWithOut() {
  return useDictStore();
}
